﻿using System.Net;

namespace Common.Class
{
    public class WebApiHelper
    {

        private static HttpClient _HttpClient;

        /// <summary>
        /// 调用WebApi服务
        /// </summary>
        /// <param name="serviceURL">服务网址</param>
        /// <param name="param">参数</param>
        /// <param name="serviceKey">调用秘钥</param>
        /// <param name="timeOut">调用超时时间(以秒为单位,默认为5)</param>
        /// <returns>调用返回数据</returns>
        public static string RunWebApiService(string serviceURL, Dictionary<string, string> param, Dictionary<string, string> headparam = null, int timeOut = 100)
        {
            DateTime _dateBegin = DateTime.Now;

            if (string.IsNullOrWhiteSpace(serviceURL))
            {
                throw new Exception("WebApi服务器URL不可为空");
            }

            string _rs = "";//返回信息


            if (_HttpClient == null)
            {
                var _handler = new HttpClientHandler()
                {
                    UseProxy = false,
                    AutomaticDecompression = System.Net.DecompressionMethods.GZip
                };
                _HttpClient = new HttpClient(_handler);
                _HttpClient.Timeout = new TimeSpan(0, 0, timeOut);
            }

            Dictionary<string, string> _postParam = new Dictionary<string, string>();
            if (param != null && param.Count > 0)
            {
                foreach (KeyValuePair<string, string> _kv in param)
                {
                    _postParam.Add(_kv.Key, WebUtility.UrlEncode(_kv.Value));
                }
            }
            HttpContent _httpContent = new StringContent(_postParam.Count > 0 ? _postParam.Select(m => m.Key + "=" + m.Value).DefaultIfEmpty().Aggregate((m, n) => m + "&" + n) : "", System.Text.Encoding.UTF8);
            _httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/x-www-form-urlencoded");

            if (headparam != null && headparam.Count > 0)
            {
                foreach (KeyValuePair<string, string> _kv in headparam)
                {
                    _httpContent.Headers.Add(_kv.Key, _kv.Value);
                }
            }

            var _response = _HttpClient.PostAsync(serviceURL, _httpContent).Result;
            if (_response != null && _response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                _rs = _response.Content.ReadAsStringAsync().Result;


            }
            else
            {
                _rs = "";
            }

            return _rs;
        }



    }
}
